const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
const multer = require('@koa/multer');
const path = require('path');
const fs = require('fs');

const app = new Koa();
const router = new Router();

// 确保 uploads 目录存在
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}

// 错误处理中间件
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        console.error('服务器错误:', err);
        ctx.status = err.status || 500;
        ctx.body = { 
            code: -1, 
            message: err.message || '服务器内部错误'
        };
    }
});

// CORS中间件
app.use(cors({
    origin: '*',
    credentials: false,
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept']
}));

// 解析请求体
app.use(bodyParser());

// 配置 multer
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadsDir);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = path.extname(file.originalname);
        cb(null, file.fieldname + '-' + uniqueSuffix + ext);
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 50 * 1024 * 1024 // 50MB
    },
    fileFilter: function (req, file, cb) {
        const allowedTypes = /mp3|wav|m4a|aac|flac|ogg/;
        const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
        const mimetype = allowedTypes.test(file.mimetype) || file.mimetype.startsWith('audio/');
        
        if (mimetype || extname) {
            return cb(null, true);
        } else {
            cb(new Error('只支持音频文件格式！'));
        }
    }
});

// 静态文件服务 - 提供 uploads 目录下的文件访问
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/uploads/')) {
        const filePath = path.join(uploadsDir, ctx.path.replace('/uploads/', ''));
        try {
            if (fs.existsSync(filePath)) {
                const stat = fs.statSync(filePath);
                ctx.set('Content-Length', stat.size);
                ctx.type = path.extname(filePath);
                ctx.body = fs.createReadStream(filePath);
                return;
            } else {
                ctx.status = 404;
                ctx.body = { code: -1, message: '文件不存在' };
                return;
            }
        } catch (err) {
            console.error('读取uploads文件失败:', err);
            ctx.status = 500;
            ctx.body = { code: -1, message: '读取文件失败' };
            return;
        }
    }
    await next();
});

// 基础路由
router.get('/', async (ctx) => {
    ctx.body = { 
        message: '音乐上传服务器正在运行',
        status: 'ok',
        timestamp: new Date().toISOString(),
        endpoints: [
            'GET /',
            'GET /health',
            'POST /api/upload/audio',
            'DELETE /api/upload/audio/:filename'
        ]
    };
});

router.get('/health', async (ctx) => {
    ctx.body = { 
        status: 'healthy',
        uptime: process.uptime(),
        timestamp: new Date().toISOString()
    };
});

// 上传音频文件
router.post('/api/upload/audio', upload.single('audio'), async (ctx) => {
    try {
        console.log('收到上传请求');
        console.log('请求头:', ctx.headers);
        console.log('文件信息:', ctx.request.file);
        
        if (!ctx.request.file) {
            ctx.status = 400;
            ctx.body = {
                code: -1,
                message: '没有上传文件'
            };
            return;
        }

        const file = ctx.request.file;
        const audioUrl = `/uploads/${file.filename}`;

        console.log('文件上传成功:', {
            originalName: file.originalname,
            filename: file.filename,
            path: file.path,
            size: file.size
        });

        ctx.status = 200;
        ctx.body = {
            code: 0,
            message: '上传成功',
            data: {
                audioUrl: audioUrl,
                filename: file.filename,
                originalName: file.originalname,
                size: file.size
            }
        };
    } catch (error) {
        console.error('上传失败:', error);
        ctx.status = 500;
        ctx.body = {
            code: -1,
            message: '上传失败: ' + error.message
        };
    }
});

// 删除音频文件
router.delete('/api/upload/audio/:filename', async (ctx) => {
    try {
        const filename = ctx.params.filename;
        const filePath = path.join(uploadsDir, filename);

        if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
            ctx.body = {
                code: 0,
                message: '删除成功'
            };
        } else {
            ctx.status = 404;
            ctx.body = {
                code: -1,
                message: '文件不存在'
            };
        }
    } catch (error) {
        console.error('删除失败:', error);
        ctx.status = 500;
        ctx.body = {
            code: -1,
            message: '删除失败: ' + error.message
        };
    }
});

// 注册路由
app.use(router.routes()).use(router.allowedMethods());

// 启动服务器
const PORT = 3000;
app.listen(PORT, '0.0.0.0', () => {
    console.log('='.repeat(50));
    console.log('🎵 音乐上传服务器启动成功！');
    console.log('='.repeat(50));
    console.log(`📍 本地访问: http://localhost:${PORT}`);
    console.log(`🌐 网络访问: http://172.29.99.148:${PORT}`);
    console.log('');
    console.log('📋 可用接口:');
    console.log(`   GET  /                    - 服务器状态`);
    console.log(`   GET  /health              - 健康检查`);
    console.log(`   POST /api/upload/audio    - 上传音频文件`);
    console.log(`   DELETE /api/upload/audio/:filename - 删除文件`);
    console.log(`   GET /uploads/:filename    - 访问上传的文件`);
    console.log('');
    console.log(`📁 上传目录: ${uploadsDir}`);
    console.log('='.repeat(50));
});

module.exports = app;